﻿using Abp.Domain.Entities.Auditing;
using Abp.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using Mall.DomainModel.IRepository.RepositoryProgram;

namespace Mall.Repository.Repository
{
    public class BaseRepository<TEntity, TPrimaryKey> : DapperRepositoryBase<TEntity, TPrimaryKey>, IRepository<TEntity, TPrimaryKey>
      where TEntity : class, IFullAudited, IEntity<TPrimaryKey>
    {
        public BaseRepository(IDapperConfiguration configuration) : base(configuration)
        {
        }

        /// <summary>
        /// 组装插入语句
        /// </summary>
        /// <param name="tbName">数据库表名</param>
        protected string CreateInertSql<T>(string tbName, List<string> noInitParamNames)
        {
            var columns = new List<string>();
            foreach (var propertyInfo in typeof(T).GetProperties())
            {
                var type = propertyInfo.PropertyType.GetTypeInfo();
                if (!type.IsInterface && (!type.IsClass || type.IsSealed) && !noInitParamNames.Contains(propertyInfo.Name))
                {
                    columns.Add(propertyInfo.Name);
                }
            }
            StringBuilder sql = new StringBuilder();
            sql.Append(string.Format("INSERT INTO {0}(", tbName));
            for (int i = 0; i < columns.Count; i++)
            {
                if (i == 0) sql.Append("`" + columns[i] + "`");
                else sql.Append(string.Format(",`{0}`", columns[i]));
            }
            sql.Append(") VALUES(");
            for (int i = 0; i < columns.Count; i++)
            {
                string comma = "";
                if (i != 0)
                {
                    comma = ",";
                }
                string columnSql = string.Format(comma + "@{0}", columns[i]);
                sql.Append(columnSql);
            }
            sql.Append(") ");
            return sql.ToString();
        }
    }
}
